from django.db import models
import pandas as pd


class Map(models.Model):
    map_file = models.FileField(upload_to='maps/', verbose_name='地图表格')
    name = models.CharField(max_length=64, default="", blank=True, verbose_name='地图名称')
    places = models.TextField(blank=True, verbose_name='地点集')

    class Meta:
        verbose_name = '地图'
        verbose_name_plural = verbose_name
        ordering = ['name']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.map_file:
            excel_file = pd.ExcelFile(self.map_file)
            sheet_list = excel_file.sheet_names
            if len(sheet_list) >= 2:
                for sheet in sheet_list:
                    self.name = sheet
                    self.places = pd.read_excel(excel_file, sheet).to_json().encode('utf-8').decode('unicode_escape')
                    super().save(*args, **kwargs)
            else:
                self.name = sheet_list[0]
                self.places = pd.read_excel(excel_file, sheet_list[0]).to_json().encode('utf-8').decode('unicode_escape')
                super().save(*args, **kwargs)
